'use strict';

import React from 'react';
import {
  StyleSheet, Text, View, TouchableOpacity, Dimensions, Image, AsyncStorage
} from 'react-native'

//第三方组件
import Icon from 'react-native-vector-icons/Ionicons'
import ImagePicker from 'react-native-image-picker'

//自定义组件
import _styles from '../common/styles'
import Header from '../common/header'
import upload from '../common/upload'

let width = Dimensions.get('window').width; //获取屏幕的宽度

let options = {
  title: '选择头像',
  cancelButtonTitle: '取消',
  takePhotoButtonTitle: '拍照',
  chooseFromLibraryButtonTitle: '从相册选择',
  quality: 0.75, //图片质量，不建议太高
  allowsEditing: true, //是否允许应用进行拉伸检查操作
  noData: false, //图片需要转为base64
  storageOptions: {
    skipBackup: true,
    path: 'images'  //存储到/Documents/[path]
  }
};

const Account = React.createClass({
  getInitialState(){
    return {
      user: this.props.user,  //属性传入的值
    }
  },

  //上传头像成功后的处理
  _uploadAvatar(file){
    let accessToken = this.state.user.accessToken;
    let timestamp = Date.now();
    let folder = 'avatar';
    let tags = 'app,avatar';

    //请求签名接口，获取签名值
    upload.getSignature(accessToken, folder, tags, timestamp, 'avatar')
      .then((signature)=>{
        //上传头像
        upload.image(file, timestamp, tags, folder, signature, (res) => {
          //解析上传后，返回内容
          if (res && res.secure_url) {
            console.log(res)
            let user = this.state.user
            user.avatar = res.secure_url;
            //this.setState({user : user});  //不需要再更新状态
            AsyncStorage.setItem('user', JSON.stringify(user));
          }
          else {
            console.log('public_id无效')
            console.log(res)
          }
        });
      });
  },

  //打开"拍照、从相册选择"的Model层
  _popImagePicker(){
    ImagePicker.showImagePicker(options, (response) => {
      if (response.didCancel) {
        console.log('User cancelled image picker');
      }
      else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      }
      else {
        //let source = {uri: response.uri};
        let data = 'data:image/jpeg;base64,' + response.data;

        this._uploadAvatar(data); //上传头像

        let user = this.state.user;
        user.avatar = data;
        this.setState({user: user});
      }
    });
  },

  render() {
    let user = this.state.user;
    return (
      <View style={_styles.container}>
        <Header title="账户中心" navigator={this.props.navigator}/>
        {
          user.avatar
            ? <View style={styles.avatarContainer}>
              <Image source={{uri:user.avatar}} style={styles.avatarBg}>
                <TouchableOpacity onPress={this._popImagePicker}>
                  <Image source={{uri:user.avatar}} style={styles.avatar} />
                </TouchableOpacity>
              </Image>
            </View>
            : <View style={styles.avatarContainer}>
              <Text style={styles.avatarTip}>添加狗狗的头像</Text>
              <TouchableOpacity onPress={this._popImagePicker}>
                <Icon name="ios-add" size={48} style={styles.avatarIcon}/>
              </TouchableOpacity>
            </View>
        }
      </View>
    )
  }
});

const styles = StyleSheet.create({
  avatarContainer: {
    height: 140,
    width: width,
    backgroundColor: '#eee',
    justifyContent: 'center',
    alignItems: 'center'
  },

  /*无头像时显示的头像区样式*/
  avatarTip: {
    fontSize: 14,
    color: '#666',
    padding: 10,
    backgroundColor: 'transparent'
  },
  avatarIcon: {
    backgroundColor: '#fff',
    borderRadius: 8,
    paddingLeft: 20,
    paddingRight: 18,
    paddingTop: 6,
    color: '#999'
  },

  /*有头像时显示的头像区域样式*/
  avatarBg: {
    height: 140,
    width: width,
    justifyContent: 'center',
    alignItems: 'center'
  },
  avatar: {
    height: width * 0.2,
    width: width * 0.2,
    borderRadius: width * 0.1
  },


});

module.exports = Account;